package utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    /*//方式一：定义成静态常量信息
    static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String URL = "jdbc:mysql://localhost:3306/dalwin_learn?serverTimezone=UTC";
    static final String USER = "root";
    static final String PASSWORD = "123456";*/

    //方式二：通过配置文件获取静态变量信息
    static String driver;
    static String url;
    static String user;
    static String password;
    static {
        Properties pro = new Properties();
        try {
            //JDBCUtils.class.getResourceAsStream("../config.properties")
            //new FileInputStream(JDBCUtils.class.getResource("../config.properties").getPath()
            //src/config.properties?报错了
            pro.load(JDBCUtils.class.getResourceAsStream("../config.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        driver = pro.getProperty("driver");
        url = pro.getProperty("url");
        user = pro.getProperty("user");
        password = pro.getProperty("password");
    }
    //获取连接方法
    public static Connection getConnection(){
        Connection con;
        try{
            Class.forName(driver);
            con = DriverManager.getConnection(url, user,password);
            return con;
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //关闭连接
    public static void close(Connection con, Statement sta){
        if (sta != null){
            try{
                sta.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (con != null){
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //关闭连接 + 结果集
    public static void close(Connection con,Statement sta,ResultSet rs){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        close(con,sta);
    }
}